import { ref } from 'vue'
import { getUserId } from './userStore'
import axios from 'axios'

// 收藏视频接口定义
export interface FavoriteVideo {
  id: number
  name: string
  img: string
  type: string
  favoriteTime: string
  user?: string
  tx?: string
  time?: string
  sj?: string // 时长（分钟）
  qk?: string // 卡路里
}

// 收藏列表
const favorites = ref<FavoriteVideo[]>([])

// 加载用户收藏
export function loadUserFavorites() {
  try {
    const userId = getUserId()
    const storageKey = `userFavorites_${userId}`
    const storedFavorites = localStorage.getItem(storageKey)
    
    if (storedFavorites) {
      favorites.value = JSON.parse(storedFavorites)
    } else {
      favorites.value = []
    }
    console.log('收藏数据加载完成:', favorites.value)
  } catch (error) {
    console.error('加载收藏失败:', error)
    favorites.value = []
  }
}

// 保存用户收藏
export function saveUserFavorites() {
  try {
    const userId = getUserId()
    const storageKey = `userFavorites_${userId}`
    localStorage.setItem(storageKey, JSON.stringify(favorites.value))
  } catch (error) {
    console.error('保存收藏失败:', error)
  }
}

// 获取所有收藏
export function getAllFavorites() {
  return favorites.value
}

// 添加收藏
export function addToFavorites(video: Omit<FavoriteVideo, 'favoriteTime'>) {
  const favoriteVideo: FavoriteVideo = {
    ...video,
    favoriteTime: new Date().toISOString().slice(0, 19).replace('T', ' ')
  }
  
  // 检查是否已收藏
  const existingIndex = favorites.value.findIndex(f => f.id === video.id)
  if (existingIndex === -1) {
    favorites.value.unshift(favoriteVideo)
    saveUserFavorites()
    return true
  }
  return false
}

// 移除收藏
export function removeFromFavorites(videoId: number) {
  const index = favorites.value.findIndex(f => f.id === videoId)
  if (index !== -1) {
    favorites.value.splice(index, 1)
    saveUserFavorites()
    return true
  }
  return false
}

// 检查是否已收藏
export function isFavorited(videoId: number) {
  return favorites.value.some(f => f.id === videoId)
}

// 按类型获取收藏
export function getFavoritesByType(type: string) {
  return favorites.value.filter(f => f.type === type)
}

// 获取收藏统计
export function getFavoriteStats() {
  const total = favorites.value.length
  const byType = {
    跑步: favorites.value.filter(f => f.type === '跑步').length,
    骑行: favorites.value.filter(f => f.type === '骑行').length,
    瑜伽: favorites.value.filter(f => f.type === '瑜伽').length,
    健身: favorites.value.filter(f => f.type === '健身').length
  }
  
  return { total, byType }
}

// 从后端同步收藏状态
export async function syncFavoritesFromBackend() {
  try {
    // 获取所有视频列表
    const response = await axios.get('http://localhost:3000/api/video-list');
    const videoList = response.data;
    
    // 筛选出已收藏的视频（gz=1）
    const favoritedVideos = videoList.filter((video: any) => video.gz === '1');
    
    // 将每个已收藏的视频添加到本地收藏中
    let syncCount = 0;
    for (const video of favoritedVideos) {
      const isAlreadyFavorited = isFavorited(video.id);
      if (!isAlreadyFavorited) {
        addToFavorites({
          id: video.id,
          name: video.name,
          img: video.img,
          type: video.type,
          user: video.user,
          tx: video.tx,
          time: video.time,
          sj: video.sj,
          qk: video.qk
        });
        syncCount++;
      }
    }
    
    console.log(`同步完成，新增${syncCount}个收藏视频`);
    return syncCount;
  } catch (error) {
    console.error('同步收藏状态失败:', error);
    return 0;
  }
}